package com.cwm.test.prototype.deep;

import java.io.*;
import java.util.Date;

public class QiTianDaSheng extends Monkey implements Cloneable, Serializable {

    public JinGuBang jinGuBang;

    public QiTianDaSheng() {
        this.birthday = new Date();
        this.jinGuBang = new JinGuBang();
    }

    /**
     * 采用的是深克隆，可能出现单例被破环的问题，和单例唱反调
     * @return
     */
    @Override
    protected Object clone() {
        return this.deepClone();
    }

    /**
     * 深克隆
     *
     * @return
     */
    public Object deepClone() {
        try {
            //内存中完成操价，对象读写，是通过字节码直接操作
//            序列化操作类似
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            ObjectOutputStream oos = null;
            oos = new ObjectOutputStream(bos);
            oos.writeObject(this);
            ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bis);
//            完整的对象
            QiTianDaSheng copy = (QiTianDaSheng) ois.readObject();
            copy.birthday = new Date();
            return copy;
        } catch (IOException | ClassNotFoundException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 浅克隆
     */
    public QiTianDaSheng shallowClone(QiTianDaSheng target) {
        QiTianDaSheng qiTianDasheng = new QiTianDaSheng();
        qiTianDasheng.height = target.height;
        qiTianDasheng.weight = target.height;
        qiTianDasheng.jinGuBang = target.jinGuBang;
        qiTianDasheng.birthday = new Date();
        return qiTianDasheng;
    }
}
